package com.yzdg.user.controller;

import com.yzdg.common.entitys.BaseResponse;
import com.yzdg.common.utils.ResultUtils;
import com.yzdg.model.auth.dtos.AuthUserDTO;
import com.yzdg.model.user.dtos.AddScoreDTO;
import com.yzdg.model.user.dtos.updateUserDTO;
import com.yzdg.model.user.entitys.UserInfo;
import com.yzdg.model.user.vos.GetUserVO;
import com.yzdg.user.service.UserInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户信息表(UserInfo)表控制层
 *
 * @author makejava
 * @since 2024-10-05 14:47:33
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserInfoController {

    @Resource
    private UserInfoService userInfoService;

    /**
     * AuthUserClient调用的方法
     * @param authUserDTO
     * @return
     */
    @PostMapping("/login")
    public BaseResponse<Long> login(@RequestBody AuthUserDTO authUserDTO) {
        log.info("AuthUserClient调用login的参数:{}",authUserDTO);
        Long id = userInfoService.login(authUserDTO);
        return ResultUtils.success(id);
    }

    /**
     * 根据id查询用户信息
     */
    @GetMapping("/{id}")
    public BaseResponse<GetUserVO> getUserById(@PathVariable("id") Long id) {
        log.info("根据id查询用户信息参数:{}", id);
        GetUserVO getUserVO = userInfoService.getUserById(id);
        return ResultUtils.success(getUserVO);
    }

    /**
     * 完善用户信息
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateUser(@RequestBody updateUserDTO updateUserDTO) {
        log.info("完善用户信息参数:{}", updateUserDTO);
        boolean flag = userInfoService.updateUser(updateUserDTO);
        return ResultUtils.success(flag);
    }

    /**
     * 用户签到
     */
    @GetMapping("/sign/{userId}")
    public BaseResponse<Boolean> sign(@PathVariable Long userId) {
        Boolean result = userInfoService.sign(userId);
        return ResultUtils.success(result);
    }

    /**
     * 增加积分
     */
    @PostMapping("/addScore")
    public BaseResponse<Boolean> addScore(@RequestBody AddScoreDTO addScoreDTO) {
        userInfoService.addScore(addScoreDTO);
        return ResultUtils.success(true);
    }

    /**
     * 获取用户积分排行榜
     */
    @GetMapping("/getUserRank")
    public BaseResponse<List<GetUserVO>> getUserRank() {
        List<UserInfo> userInfos = userInfoService.queryHighScore();
        // 类型转换
        List<GetUserVO> collect = userInfos.stream().map(item -> {
            GetUserVO getUserVO = new GetUserVO();
            BeanUtils.copyProperties(item, getUserVO);
            // 将id转为字符串，便于前端接收
            getUserVO.setLeiId(String.valueOf(item.getLeiId()));
            return getUserVO;
        }).collect(Collectors.toList());
        return ResultUtils.success(collect);
    }

}
